package com.treasure.infrastructure.domain.extraction.vector;

import com.alibaba.dashscope.exception.NoApiKeyException;
import com.treasure.common.model.SessionUser;
import com.treasure.common.model.SessionUserHolder;
import com.treasure.domain.domain.RelatedTextExtractionDomainService;
import com.treasure.domain.domain.entity.SegmentDocEntity;
import com.treasure.common.exception.ServiceException;
import com.treasure.common.types.Question;
import com.treasure.infrastructure.model.doc.SegmentVectorDocBean;
import com.treasure.infrastructure.repository.extraction.vector.SegmentVectorDocRepository;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author sunhongmin
 * @date 2023/8/27 10:03
 * @description
 */
@Service
@Slf4j
public class RelatedTextExtractionVectorDomainServiceImpl implements RelatedTextExtractionDomainService {

    @Autowired
    private SegmentVectorDocRepository segmentVectorDocRepository;

    @Override
    public List<SegmentDocEntity> relatedTextExtraction(Question question) {
        List<SegmentVectorDocBean> segmentVectorDocBeans = null;
        SessionUser sessionUser = SessionUserHolder.getAndCheckSessionUser();
        try {
            segmentVectorDocBeans = segmentVectorDocRepository.searchByVector(sessionUser.getCorpId(), question.getValue());
        } catch (NoApiKeyException e) {
            log.error("relatedTextExtraction NoApiKeyException e: ", e);
            throw new ServiceException(e.getMessage());
        }
        if (CollectionUtils.isEmpty(segmentVectorDocBeans)) {
            return Collections.emptyList();
        }

        List<SegmentDocEntity> result = new ArrayList<>(segmentVectorDocBeans.size());
        for (SegmentVectorDocBean segmentESDocBean : segmentVectorDocBeans) {
            SegmentDocEntity segmentDocEntity = getSegmentDocEntity(segmentESDocBean);
            result.add(segmentDocEntity);
        }
        return result;
    }

    @NotNull
    private static SegmentDocEntity getSegmentDocEntity(SegmentVectorDocBean segmentESDocBean) {
        SegmentDocEntity segmentDocEntity = new SegmentDocEntity();
        segmentDocEntity.setId(segmentDocEntity.getId());
        segmentDocEntity.setCorpId(segmentDocEntity.getCorpId());
        segmentDocEntity.setUserId(segmentDocEntity.getUserId());
        segmentDocEntity.setDocName(segmentESDocBean.getDocName());
        segmentDocEntity.setPassages(segmentESDocBean.getPassages());
        return segmentDocEntity;
    }
}
